import React, {PropsWithChildren, useState} from 'react'
import {Button, Popover, Select, Space} from "antd";

export interface SingleSelectPopoverProps<Key> extends PropsWithChildren {
    title: string
    onConfirm: (value?: Key) => Promise<void>
    placeholder?: string
    initialValue?: Key
    options: {
        value: Key,
        label: string,
    }[]
    required?: boolean
}

const SingleSelectPopover = <Key, >({
                                        title,
                                        onConfirm,
                                        placeholder,
                                        children,
                                        initialValue,
                                        options,
                                        required
                                    }: SingleSelectPopoverProps<Key>) => {
    const [loading, setLoading] = useState(false)
    const [open, setOpen] = useState(false)
    const [selectedValue, setSelectedValue] = useState<Key | undefined>(initialValue)
    return <>
        <Popover open={open} trigger={"click"} title={title} onOpenChange={visible => setOpen(visible)} content={
            <Space direction={"vertical"}>
                <Select value={selectedValue} onChange={v=>{
                    setSelectedValue(v)
                }} placeholder={placeholder}>
                    {options.map(option => <Select.Option key={option.value + ""}
                                                          value={option.value}>{option.label}</Select.Option>)}
                </Select>
                <Button loading={loading}
                        disabled={required && !selectedValue}
                        onClick={async () => {
                            setLoading(true)
                            try {
                                await onConfirm(selectedValue)
                                setOpen(false)
                                setSelectedValue(undefined)
                            } finally {
                                setLoading(false)
                            }
                        }}>确定</Button>
            </Space>
        }>
            {children}
        </Popover>
    </>
}

export default SingleSelectPopover


